<template>
  <a-modal
    :open="visible"
    title="协同编辑图片"
    width="1000px"
    :footer="null"
    centered
    @cancel="handleClose"
  >
    <div class="collaborative-edit-container">
      <a-row :gutter="24">
        <!-- 左侧：图片预览区域 -->
        <a-col :span="16">
          <div class="picture-preview-section">
            <div class="preview-header">
              <h4>{{ pictureData?.name || '图片预览' }}</h4>
              <a-tag v-if="currentEditor" color="green">
                <template #icon><EditOutlined /></template>
                {{ currentEditor.userName }} 正在编辑
              </a-tag>
              <a-tag v-else color="default">无人编辑</a-tag>
            </div>

            <div class="preview-container">
              <div
                class="preview-wrapper"
                :style="{
                  transform: `rotate(${rotation}deg) scale(${scale})`,
                  transition: 'transform 0.3s ease',
                }"
              >
                <img
                  v-if="pictureData?.url"
                  :src="pictureData.url"
                  :alt="pictureData.name"
                  class="preview-image"
                />
              </div>
            </div>

            <!-- 编辑操作按钮 -->
            <div class="edit-actions">
              <a-space size="large">
                <a-button
                  type="primary"
                  size="large"
                  :icon="h(UndoOutlined)"
                  :disabled="!canEdit"
                  @click="handleRotateLeft"
                >
                  向左旋转
                </a-button>
                <a-button
                  type="primary"
                  size="large"
                  :icon="h(RedoOutlined)"
                  :disabled="!canEdit"
                  @click="handleRotateRight"
                >
                  向右旋转
                </a-button>
                <a-button
                  size="large"
                  :icon="h(ZoomInOutlined)"
                  :disabled="!canEdit"
                  @click="handleZoomIn"
                >
                  放大
                </a-button>
                <a-button
                  size="large"
                  :icon="h(ZoomOutOutlined)"
                  :disabled="!canEdit"
                  @click="handleZoomOut"
                >
                  缩小
                </a-button>
              </a-space>
            </div>

            <!-- 编辑控制 -->
            <div class="edit-control">
              <a-button
                v-if="!wsConnection?.isCurrentUserEditing()"
                type="primary"
                size="large"
                :disabled="!!currentEditor"
                :loading="!isConnected"
                @click="handleEnterEdit"
              >
                <template #icon><EditOutlined /></template>
                {{ currentEditor ? '有人正在编辑' : '开始编辑' }}
              </a-button>
              <a-button v-else danger size="large" @click="handleExitEdit">
                <template #icon><CloseOutlined /></template>
                退出编辑
              </a-button>
            </div>
          </div>
        </a-col>

        <!-- 右侧：在线用户和消息区域 -->
        <a-col :span="8">
          <div class="sidebar-section">
            <!-- 在线用户列表 -->
            <div class="online-users">
              <h4>
                <TeamOutlined style="margin-right: 8px" />
                在线成员 ({{ onlineUsers.size }})
              </h4>
              <a-list size="small" :data-source="Array.from(onlineUsers.values())">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-list-item-meta>
                      <template #avatar>
                        <a-avatar :src="item.userAvatar" :alt="item.userName">
                          {{ item.userName.charAt(0).toUpperCase() }}
                        </a-avatar>
                      </template>
                      <template #title>
                        <span>{{ item.userName }}</span>
                        <a-tag
                          v-if="item.isEditing"
                          color="green"
                          size="small"
                          style="margin-left: 8px"
                        >
                          编辑中
                        </a-tag>
                      </template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </div>

            <!-- 操作日志 -->
            <div class="message-log">
              <h4>
                <HistoryOutlined style="margin-right: 8px" />
                操作日志
              </h4>
              <div class="message-list">
                <div
                  v-for="(msg, index) in recentMessages"
                  :key="index"
                  class="message-item"
                  :class="`message-${msg.type?.toLowerCase()}`"
                >
                  <div class="message-content">
                    <a-avatar
                      v-if="msg.user"
                      :src="msg.user.userAvatar"
                      size="small"
                      style="margin-right: 8px"
                    >
                      {{ msg.user.userName.charAt(0).toUpperCase() }}
                    </a-avatar>
                    <span>{{ msg.message }}</span>
                  </div>
                </div>
                <a-empty
                  v-if="recentMessages.length === 0"
                  :image="false"
                  description="暂无操作记录"
                />
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch, h, shallowRef } from 'vue'
import { message } from 'ant-design-vue'
import {
  EditOutlined,
  TeamOutlined,
  HistoryOutlined,
  UndoOutlined,
  RedoOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  CloseOutlined,
} from '@ant-design/icons-vue'
import { usePictureEditWebSocket, type OnlineUser } from '@/composables/usePictureEditWebSocket'
import type { PictureVO } from '@/types/picture'

interface Props {
  visible: boolean
  pictureData: PictureVO | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

// 图片变换状态
const rotation = ref(0) // 旋转角度
const scale = ref(1) // 缩放比例

// 图片ID - 使用 computed 保持响应式
const pictureId = computed(() => props.pictureData?.id?.toString() || '')

// WebSocket连接实例
const wsConnection = shallowRef<ReturnType<typeof usePictureEditWebSocket> | null>(null)

// 响应式状态
const isConnected = computed(() => wsConnection.value?.isConnected.value ?? false)
const onlineUsers = computed(
  () => wsConnection.value?.onlineUsers.value ?? new Map<string, OnlineUser>(),
)
const currentEditor = computed(() => wsConnection.value?.currentEditor.value ?? null)
const recentMessages = computed(() => wsConnection.value?.getRecentMessages(10) ?? [])

// 是否可以编辑
const canEdit = computed(() => wsConnection.value?.isCurrentUserEditing() && isConnected.value)

// 监听visible变化
watch(
  () => props.visible,
  async (newVal) => {
    if (newVal && pictureId.value) {
      console.log('=== 协同编辑诊断信息 ===')
      console.log('1. 图片信息:', {
        pictureId: pictureId.value,
        pictureIdType: typeof pictureId.value,
        pictureData: props.pictureData,
        spaceId: props.pictureData?.spaceId,
        name: props.pictureData?.name,
      })

      // 打开模态框时初始化WebSocket连接
      // 确保pictureId是字符串形式，避免精度丢失
      const pictureIdStr = String(props.pictureData?.id || '')
      console.log('2. 使用的pictureId字符串:', pictureIdStr, '长度:', pictureIdStr.length)

      // 检查是否有登录信息
      console.log('3. 当前URL:', window.location.href)
      console.log('4. 检查Cookie:', document.cookie ? '有Cookie' : '无Cookie')

      if (!pictureIdStr || pictureIdStr === 'undefined' || pictureIdStr === 'null') {
        console.error('❌ 错误：pictureId无效！')
        message.error('图片ID无效，无法建立连接')
        return
      }

      wsConnection.value = usePictureEditWebSocket(pictureIdStr)

      // 连接WebSocket
      await wsConnection.value.connect()
    } else {
      // 关闭模态框时断开连接
      if (wsConnection.value) {
        wsConnection.value.disconnect()
        wsConnection.value = null
      }
      // 重置图片状态
      rotation.value = 0
      scale.value = 1
    }
  },
)

// 监听其他用户的编辑操作
watch(
  () => recentMessages.value,
  (newMessages) => {
    if (newMessages.length > 0) {
      const latestMessage = newMessages[0]
      // 只同步其他用户的编辑操作
      if (
        latestMessage.type === 'EDIT_ACTION' &&
        latestMessage.editAction &&
        !wsConnection.value?.isCurrentUserEditing()
      ) {
        applyEditAction(latestMessage.editAction)
      }
    }
  },
  { deep: true },
)

// 应用编辑动作（用于同步其他用户的操作）
const applyEditAction = (action: string) => {
  switch (action) {
    case 'ROTATE_LEFT':
      rotation.value -= 90
      break
    case 'ROTATE_RIGHT':
      rotation.value += 90
      break
    case 'ZOOM_IN':
      scale.value = Math.min(scale.value + 0.2, 3)
      break
    case 'ZOOM_OUT':
      scale.value = Math.max(scale.value - 0.2, 0.2)
      break
  }
}

// 向左旋转
const handleRotateLeft = () => {
  if (!canEdit.value) {
    message.warning('请先开始编辑')
    return
  }
  rotation.value -= 90
  wsConnection.value?.executeEditAction('ROTATE_LEFT')
}

// 向右旋转
const handleRotateRight = () => {
  if (!canEdit.value) {
    message.warning('请先开始编辑')
    return
  }
  rotation.value += 90
  wsConnection.value?.executeEditAction('ROTATE_RIGHT')
}

// 放大
const handleZoomIn = () => {
  if (!canEdit.value) {
    message.warning('请先开始编辑')
    return
  }
  scale.value = Math.min(scale.value + 0.2, 3)
  wsConnection.value?.executeEditAction('ZOOM_IN')
}

// 缩小
const handleZoomOut = () => {
  if (!canEdit.value) {
    message.warning('请先开始编辑')
    return
  }
  scale.value = Math.max(scale.value - 0.2, 0.2)
  wsConnection.value?.executeEditAction('ZOOM_OUT')
}

// 开始编辑
const handleEnterEdit = async () => {
  if (!isConnected.value) {
    message.error('连接已断开，请重新打开')
    return
  }

  try {
    message.loading({ content: '正在请求编辑权限...', key: 'enterEdit', duration: 0 })
    await wsConnection.value?.enterEdit()
    message.success({ content: '获得编辑权限，可以开始编辑了！', key: 'enterEdit' })
  } catch (error: unknown) {
    const errorMsg =
      error instanceof Error ? error.message : '获取编辑权限失败，可能有其他用户正在编辑'
    message.error({
      content: errorMsg,
      key: 'enterEdit',
    })
  }
}

// 退出编辑
const handleExitEdit = () => {
  wsConnection.value?.exitEdit()
}

// 关闭模态框
const handleClose = () => {
  if (wsConnection.value?.isCurrentUserEditing()) {
    wsConnection.value.exitEdit()
  }
  emit('update:visible', false)
}
</script>

<style scoped>
.collaborative-edit-container {
  padding: 16px 0;
}

.picture-preview-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fafafa;
  border-radius: 8px;
}

.preview-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 400px;
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  max-height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
}

.edit-actions {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.edit-control {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}

.sidebar-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

.online-users,
.message-log {
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
}

.online-users h4,
.message-log h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-item {
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  font-size: 13px;
  border-left: 3px solid #d9d9d9;
}

.message-content {
  display: flex;
  align-items: center;
}

.message-info {
  border-left-color: #1890ff;
}

.message-enter_edit {
  border-left-color: #52c41a;
}

.message-exit_edit {
  border-left-color: #faad14;
}

.message-edit_action {
  border-left-color: #722ed1;
}

.message-error {
  border-left-color: #f5222d;
}

:deep(.ant-list-item) {
  padding: 8px 0;
}

:deep(.ant-list-item-meta-title) {
  display: flex;
  align-items: center;
  margin-bottom: 0;
}
</style>
